<template>
    <div class="activity-list">
        <el-row>
            <el-col :span="6">
                <div class="left-box">
                    <el-tabs v-model="box_index_key" @tab-click="handleClick">
                        <el-tab-pane v-for="(item, index) in box_list_arr" :key="index" :label="item.label"
                            :name="item.name">
                            <div class="select-box flex_between">
                                <el-select size="mini" class="select-w" v-model="shopid_yd" placeholder="请选择"
                                    @change="selectFun">
                                    <el-option v-for="item in getYunShopList" :key="item.id" :label="item.name"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                            </div>
                            <!-- 列表 -->
                            <div :style="{ height: stateHooks.leftHeight + 'px', overflow: 'hidden' }">
                                <LeftList :templates="templates" :listData="listData"
                                    :selectedIndex.sync="selectedIndex" @loadFun="loadFun" ref="leftListRef"
                                    :lLoading="lLoading" :lNoMore="lNoMore" @clickItem="clickItem">
                                    <div slot-scope="{row}" slot="title" class="flex_between">
                                        <div>
                                            <el-tag :type="'danger'" size="mini">{{ row.grade }}</el-tag>
                                            <span class="bold ml5">{{ row.title }}</span>
                                        </div>
                                        <span>{{ row.status_txt }}</span>
                                    </div>
                                      <div slot-scope="{row}" slot="num_od" class="flex_row total-give">
                                            <div>
                                                <span class="">会员数量</span>
                                                <span class="ml5">{{ row.num_u || '-' }}</span>
                                            </div>
                                            <div class="ml20">
                                                <span class="">购买次数</span>
                                                <span class="ml5">{{ row.num_od || '-' }}</span>
                                            </div>
                                            <div class="ml20">
                                                <span class="">总金额</span>
                                                <span class="ml5">{{ row.price_i || '-' }}</span>
                                            </div>
                                        </div>
                                </LeftList>
                            </div>
                        </el-tab-pane>
                    </el-tabs>
                    <div class="iconBox">
                        <text class="icon-font search-icon" @click="addActivityList">&#xe606;</text>
                    </div>
                </div>
            </el-col>
            <el-col :span="18">
                <div class="rigth-box">
                    <template v-if="isEdit">
                        <addOrEdit :getYunShopList="getYunShopSeleteList" ref="addOrEditRef" @backFun="backFun"
                            @addTpBmFun="addTpBmFun" :detailID="detailID" :isDisbableInfo="isDisbableInfo">
                        </addOrEdit>
                    </template>
                    <template v-else>
                        <detaill ref="detaillRef" :detailID="detailID" @editStopTpBmFun="editStopTpBmFun"
                            @stopTpBmFun="stopTpBmFun"></detaill>
                    </template>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance, watch } from '@vue/composition-api'
import LeftList from "@/pages/memberLevel/components/leftList.vue"
import addOrEdit from "@/pages/memberLevel/components/addOrEdit.vue"
import detaill from "@/pages/memberLevel/components/detaill.vue"
import config from "@/js/conf/Config.js"
import { useCommonHooks } from '@/hooks/useCommonHooks.js'

const maxPnum = 20

// 获取当前组件实例
const { proxy } = getCurrentInstance()

// 使用全局状态
const { stateHooks } = useCommonHooks()

const lLoading = ref(false)
const lNoMore = ref(false)
const isEdit = ref(false)

// 如果是编辑页面，设置某些值不能编辑
const isDisbableInfo = ref({
    type: false,
})

const box_index_key = ref('1')
const selectedIndex = ref(0)
const box_list_arr = ref([{
    label: "进行中",
    name: '1',
}, {
    label: "未开始",
    name: '2',
}])

const templates = ref([
    {
        type: "slot",
        key: "title",
    },
    {
        type: "init",
        key: "shop_name",
    },
    {
        type: "init",
        key: "zk_title",
    },
    {
        type: "init",
        key: "up_title",
    },
    {
        type: "slot",
        key: "num_od",
    }
])

const listData = ref([])
const detailID = ref('')

const getYunShopList = ref([{
    name: "全部云店",
    id: 0,
}])
const getYunShopSeleteList = ref([])

const shopid_yd = ref(0)
const pfrom = ref(0)
const leftListRef = ref(null)
const addOrEditRef = ref(null)
const detaillRef = ref(null)

const addActivityList = () => {
    selectedIndex.value = null
    isEdit.value = true
    isDisbableInfo.value.type = false
    if (addOrEditRef.value) {
        isDisbableInfo.value.type = false
        addOrEditRef.value.restFun()
        addOrEditRef.value.objectForm.act = 'add'
    }
}

// 状态切换
const handleClick = (e) => {
    isEdit.value = false
    selectedIndex.value = 0
    box_index_key.value = box_list_arr.value[e.index].name
    if (detailID.value && detaillRef.value) {
        detaillRef.value.objectForm = {}
        detaillRef.value.userList = []
    }
    isDisbableInfo.value.type = true
    refreshFun()
    getEventLs(true)
}

const refreshFun = () => {
    lNoMore.value = false
    lLoading.value = false
    pfrom.value = 0
    detailID.value = ''
    listData.value = []

}

const selectFun = (e) => {
    getEventLs(true)
}

const loadFun = () => {
    if (lNoMore.value) return
    pfrom.value += 20
    getEventLs(false)
}

const getEventLs = async (t) => {
    lLoading.value = true
    if (t == true) {
        pfrom.value = 0
        listData.value = []
    }
    let param = {
        shopid_yd: shopid_yd.value,
        st: box_index_key.value,
        pnum: maxPnum,
        pfrom: pfrom.value,
    }
    try {
        let res = await proxy.$api({ url: config.yx_ugd_event_ls, data: param })
        if (res.status == 1 && res.data.ls) {
            listData.value.push(...res.data.ls)
            // 确保索引在有效范围内
            const validIndex = Math.min(selectedIndex.value, listData.value.length - 1)
            detailID.value = listData.value[validIndex]?.id
            if (res.status == 1 && res.data.ls.length < maxPnum) {
                lNoMore.value = true
            } else {
                lNoMore.value = false
            }
        } else {
            lNoMore.value = true
        }
    } catch (error) {
        lLoading.value = false
        lNoMore.value = true
    } finally {
        lLoading.value = false
    }
}

const getDetail = async () => {
    const res = await proxy.$api({ url: config.yx_ugd_event_info, data: { id: detailID.value } })
    if (res.status === 1 && res.data) {
        const data = res.data
        // 使用 Object.assign 来保持响应性
        Object.assign(listData.value[selectedIndex.value], data)
    }
}

//  获取云店列表
const getYunShopLsFun = async () => {
    let param = {}
    try {
        let res = await proxy.$api({ url: config.YUN_SHOP_LS, data: param })
        if (res.status == 1) {
            getYunShopList.value.push(...res.data)
            getYunShopSeleteList.value = res.data
        }
    } catch (error) {
    }
}

// 新增投票/报名
const addTpBmFun = (e) => {
    if (e.type == 'add') {
        selectedIndex.value = 0
        refreshFun()
        getEventLs(true)
    } else {
        isEdit.value = false
        getDetail()
        if (isDisbableInfo.value.type) {
            isDisbableInfo.value.type = true
        } else if (!isDisbableInfo.value.type) {
            isDisbableInfo.value.type = false
        }
        if (detailID.value && detaillRef.value) {
            detaillRef.value.getDetail()
            detaillRef.value.getUserList()
        }
    }
}

const backFun = (e) => {
    isEdit.value = false
}

// 编辑投票/报名
const editStopTpBmFun = (e) => {
    if (e.type == 'edit') {
        isEdit.value = true
        if (box_index_key.value == '2') {
            isDisbableInfo.value.type = true
        }
    } else {
        isEdit.value = false
        getDetail()
        if (isDisbableInfo.value.type) {
            isDisbableInfo.value.type = true
        } else if (!isDisbableInfo.value.type) {
            isDisbableInfo.value.type = false
        }
        if (detailID.value && detaillRef.value) {
            detaillRef.value.getDetail()
            detaillRef.value.getUserList()
        }
    }
}

const clickItem = (index) => {
    isEdit.value = false
    selectedIndex.value = index
    if (detailID.value && detaillRef.value) {
        detaillRef.value.pfrom = 0
        detaillRef.value.userList = []
    }
}

// 正确使用 watch
watch(() => selectedIndex.value, (newValue) => {
    console.log("newValue=", newValue)
    if (newValue == null) {
        detailID.value = ''
        return
    }
    if (newValue) {
        selectedIndex.value = newValue
    }
    if (listData.value && listData.value.length > 0) {
        // 确保索引在有效范围内
        const validIndex = Math.min(newValue, listData.value.length - 1)
        const selectedItem = listData.value[validIndex]
        if (selectedItem && selectedItem.id) {
            detailID.value = selectedItem.id
        } else {
            detailID.value = ''
        }
    } else {
        detailID.value = ''
    }
}, {
    immediate: true
})

// 活动记录
const activityList = (row) => {
    // TODO: Implement activity list functionality
}

onMounted(() => {
    getEventLs()
    getYunShopLsFun()
})

</script>

<style lang="scss" scoped>
div {
    box-sizing: border-box;
}

.activity-list {

    .left-box,
    .rigth-box {
        width: 100%;
        padding: 10px 10px 0 10px;
        height: 100vh;
        position: relative;
        border-right: 1px solid #e6e6e6;

        .iconBox {
            position: absolute;
            top: 0px;
            right: 13px;
            font-size: 26px;
            cursor: pointer;

            .search-icon {
                font-size: 20px;
                color: #333;
            }
        }

        .marketing-add {
            width: 100%;
        }
    }

    .status_txt {
        position: absolute;
        right: 20px;
        top: 33px;
    }

    .list_btn {
        position: absolute;
        bottom: 10px;
        right: 20px;
        z-index: 9;
    }
}

.ellipsis2 {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
}

.left-box {
    .select-w {
        width: 49%;
    }
}

.total-give {
    border-top: 1px solid #e6e6e6;
    padding-top: 10px;
    margin-top: 10px;
}

</style>